package edu.ped.android.nfc;

import edu.ped.android.utils.NFCUtil;
import edu.ped.android.utils.PayloadTag;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class TimeDistanceActivity extends GDActivity{
	TextView tv;
	Button clear;
	Long previousTime;

	@Override
	protected void onResume() {
		super.onResume();
		NFCUtil.getNFCFocus(this);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setActionBarContentView(R.layout.activity_time_distance);

		/*Title Bar*/
		ActionBarManager.initActionBar(this,ActionBarManager.TIMEDISTANCE);

		tv = (TextView) findViewById(R.activity_time_distance.textView1);
		clear= (Button)	 findViewById(R.activity_time_distance.button1);

		OnClickListener action = new OnClickListener() {

			public void onClick(View v) {
				tv.setText("");
			}
		};
		clear.setOnClickListener(action);
		previousTime = System.currentTimeMillis();
	}

	protected void onNewIntent(Intent intent) {
		String actionIntent= intent.getAction();
		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(actionIntent)
				|| NfcAdapter.ACTION_TAG_DISCOVERED.equals(actionIntent)
				|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(actionIntent)) {

			long time = System.currentTimeMillis();

			long delta = time - previousTime;

			tv.setText(tv.getText().toString()+getResources().getString(R.string.detect)+" "+delta);

			// --> TIME 2 START
			previousTime = System.currentTimeMillis();		
			PayloadTag messages;
			try {			
				messages = NFCUtil.readTagObject(intent);
				time = System.currentTimeMillis();
				// <-- TIME 2 END

				delta = time - previousTime;

				tv.setText(tv.getText().toString()+ " - "+getResources().getString(R.string.readObj)+" "+ delta);
				previousTime = System.currentTimeMillis();

				NFCUtil.writeTagObject(messages, intent);
				tv.setText(tv.getText().toString()+ " - "+getResources().getString(R.string.writeObj) + " "+NFCUtil.delta+"\n");
				
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
	
	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		if(!ActionBarManager.handleActionBar(this, item, position))
			return super.onHandleActionBarItemClick(item, position);
		return true;
	}
}
